<template>
  <div class="container" ref="mainCon">
    <div class="titleBoxOut">
      <div class="titleBox clearfix">
        <div class="fl">
          <span class="blockTitle">
            <i class="icon iconfont iconfanhui1" @click="goBack"></i>
            {{ projectName || '--' }}
          </span>
          <p>
            <span class="code"
              >开户银行：<span>{{ bankName || '--' }}</span></span
            >
            <span class="code"
              >银行网点：<span>{{ bankSiteName || '--' }}</span></span
            >
            <span class="code"
              >专户账号：
              <span>
                {{
                  isDisplay
                    ? account.replace(
                        /^([\s\S]{3})[\s\S]*?([\s\S]{3})$/,
                        '$1**** ****$2'
                      )
                    : account
                }}
              </span>
            </span>
            <el-button
              type="primary"
              style="
                padding: 2px;
                width: 40px;
                background: #009588;
                border: 1px solid #009588;
              "
              @click="doDisplay"
              >{{ isDisplay ? '显示' : '隐藏' }}</el-button
            >
          </p>
        </div>
      </div>
    </div>
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="发薪年月" class="row-padding-bottom">
              <el-date-picker
                v-model="date"
                type="month"
                placeholder="选择年月"
                value-format="yyyy-MM"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="工资表状态" class="row-padding-bottom">
              <el-select
                v-model="filterField.status"
                filterable
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in salaryStatusOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item>
            <!-- <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="commonBtn"
            ></el-button> -->
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
          <div style="display: inline-block; margin-top: 5px">
            <el-link type="primary" v-if="bankSalaryImport" @click="downLoad()"
              >回传代发数据导入模板下载</el-link
            >
          </div>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column label="工资表信息">
            <template slot-scope="scope">
              <p style="olor: rgb(96, 98, 102); font-weight: bold">
                {{ scope.row.year || '--' }}年{{
                  scope.row.month || '--'
                }}月第{{ scope.row.batchNo || '--' }}批次工资
              </p>
              <p style="color: #999; font-size: 12px">
                创建日期： {{ scope.row.createTime || '--' }}
              </p>
              <p style="color: #999; font-size: 12px">
                订单号： {{ scope.row.sequenceCode || '--' }}
              </p>
            </template>
          </el-table-column>
          <el-table-column label="应发/到账工资总额(元)" align="center">
            <template slot-scope="scope">
              <p>
                ￥{{ scope.row.shouldPay || '0' }}/￥{{
                  scope.row.bankActPay || '--'
                }}
              </p>
            </template>
          </el-table-column>
          <el-table-column label="应发/到账总人数" align="center">
            <template slot-scope="scope">
              <p>
                {{ scope.row.shouldPayTotal || '0' }}/{{
                  scope.row.bankActPayTotal || '--'
                }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            prop="statusDesc"
            label="工资表状态"
            align="center"
            :formatter="formatTd"
          ></el-table-column>
          <!-- <el-table-column label="操作" align="left" fixed="right" v-if="isOperate"> -->
          <el-table-column label="操作" align="left" fixed="right">
            <template slot-scope="scope">
              <el-link
                type="primary"
                v-show="isShowDetail"
                @click="toDetail(scope.$index, scope.row)"
                >查看详情</el-link
              >
              <el-link
                type="primary"
                @click="toUploadFile(scope.$index, scope.row)"
                >查看附件</el-link
              >
              <div
                class="manualPostbackBox"
                v-if="scope.row.status == 'NO_ISSUE' && bankSalaryImport"
              >
                <div
                  v-if="
                    !scope.row.bankManualStatus ||
                    scope.row.bankManualStatus == 'NO_IMPORT'
                  "
                >
                  <el-link type="primary">手动回传</el-link>
                  <form class="upLoadDom">
                    <input
                      id="waterImportfileChangeCz"
                      type="file"
                      name="multipartFile"
                      @change="
                        waterImportfileChangeCz($event, scope.$index, scope.row)
                      "
                      title="手动回传"
                    />
                  </form>
                </div>
              </div>
              <el-link
                type="primary"
                v-if="
                  (bankSalaryImport &&
                    scope.row.bankManualStatus == 'NO_SYNC') ||
                  scope.row.bankManualStatus == 'SYNCHRONIZED'
                "
                @click="toClearNetData(scope.row)"
                >清空实发数据</el-link
              >
              <el-link
                type="primary"
                v-if="
                  bankSalaryImport && scope.row.bankManualStatus == 'NO_SYNC'
                "
                @click="toSyncData(scope.row)"
                >确认同步</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
      <!-- 上传合同附件 -->
      <el-dialog
        title="附件"
        :visible.sync="uploadContract"
        :modal-append-to-body="false"
        :append-to-body="true"
      >
        <div class="uploadBox" v-show="uploadImg.length < 1">暂无附件</div>
        <div>
          <ul class="clearfix imgStyle">
            <li class="fl" v-for="(item, index) of uploadImg" :key="index">
              <el-image
                style="width: 100px; height: 100px"
                :src="item.url ? item.url : item.absolutePath"
                :preview-src-list="srcList"
                @click="enlargeImg(index)"
              ></el-image>
            </li>
          </ul>
        </div>
      </el-dialog>
    </div>
    <el-dialog
      title="上传失败"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
    >
      <div class="errorNoticeBox">
        <i class="icon iconfont iconshibai1"></i>
      </div>
      <div v-html="errorNotice" class="errorBox"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="closeDialog" class="save"
          >确认</el-button
        >
        <el-button @click.native="closeDialog" class="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import common from '../../kits/common'
import scrollTable from '@/mixin/scrollTable.js'

export default {
  name: 'czSalaryPayBatchList',
  mixins: [scrollTable],
  props: ['message', 'detailProjectName'],
  data() {
    return {
      titleText: '',
      back: true,
      isOperate: true, //项目看板的工资操作无
      projectId: '',
      projectName: '',
      date: [],
      salaryStatusOptions: [], //工资表状态
      //表格数据
      tableList: [],
      requestUrl: 'api-su/cs/salary/expand/list',
      areaId: '', //区域
      //搜索条件
      filterField: {
        projectId: '',
        year: '',
        month: '',
        status: '',
      },
      isShow: false, //列表加载
      loading: true,
      uploadImg: [],
      saveImgArr: [],
      srcList: [],
      oldSrcList: [],
      canLogin: false, //保存loading
      uploadContract: false, //上传合同附件
      salaryId: '', //工资id
      formVisible: false,
      flieUpload: {
        projectId: '',
      },
      errorNotice: '',
      isShowDetail: '',
      exportBtn: '',
      bankName: '',
      bankSiteName: '',
      account: '',
      isDisplay: true, //是否隐藏
      isCz: false,
      bankSalaryImport: false,
    }
  },
  created() {
    //从项目看板中的工资
    if (this.message === 'salary') {
      this.isOperate = false
    }
    this.projectId = this.$route.query.projectId
    this.projectName = this.$route.query.projectName
      ? this.$route.query.projectName
      : this.detailProjectName
    this.filterField.projectId = this.$route.query.projectId
    this.getSalaryStatus()
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.isShowDetail =
      this.$store.state.buttonLimitsArr.indexOf('mCsSalaryList:detail') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('mProjectList:detail') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('projectList:detail') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('bankSalaryPayList:detail') > -1
    this.exportBtn =
      this.$store.state.buttonLimitsArr.indexOf('mCsSalaryList:export') > -1
    //获取专户银行信息
    this.getBankInfo()
    if (this.isCzUser()) {
      this.isCz = true
    }
    this.getBankSalaryDetail()
  },
  computed: {
    isHefeng() {
      return this.$store.state.isHefeng
    },
  },
  mounted() {
    if (this.message === 'salary') {
      $('.mainCon').css('top', '0')
    }
  },
  methods: {
    doDisplay() {
      this.isDisplay = !this.isDisplay
    },
    toUploadFile(index, row) {
      this.salaryId = row.id
      this.uploadImg = []
      this.saveImgArr = []
      this.srcList = []
      this.oldSrcList = []
      this.getUploadSearchImg(this.salaryId)
      this.uploadContract = true
    },
    // 获取附件查询图片
    getUploadSearchImg(salaryId) {
      var data = {
        associatedName: 'T_CS_SALARY',
        associatedId: salaryId,
      }
      this.axios({
        method: 'post',
        url: 'api-f/files/list',
        data: data,
      })
        .then((response) => {
          // this.bankData = response.data;
          if (!response.data.hasError) {
            this.uploadImg = response.data.result
            for (var i = 0; i < this.uploadImg.length; i++) {
              this.saveImgArr.push({
                originalName: this.uploadImg[i].originalName,
                relativePath: this.uploadImg[i].relativePath,
                fileSize: this.uploadImg[i].fileSize,
                fileType: this.uploadImg[i].fileType,
              })
              this.srcList.push(this.uploadImg[i].absolutePath)
              this.oldSrcList.push(this.uploadImg[i].absolutePath)
            }
          } else {
            this.$message({
              type: 'error',
              message: '数据获取失败',
            })
          }
        })
        .catch((error) => {})
    },
    enlargeImg(index) {
      this.srcList = this.oldSrcList
      var demo = this.srcList
      var frontArr = demo.slice(0, index)
      var behindArr = demo.slice(index, demo.length)
      var list = behindArr.concat(frontArr)
      this.srcList = list
    },
    goBack() {
      let path, oldUrl
      if (
        this.$route.query.delSalary &&
        this.$route.query.delSalary == 'delSalaryList'
      ) {
        ;(path = '/home/delSalary/salaryList'),
          (oldUrl = '/home/delSalary/salaryList')
      } else {
        ;(path = '/home/salaryDf/czSalaryPayList'),
          (oldUrl = '/home/salaryDf/czSalaryPayBatchList')
      }
      this.$router.push({
        path: path,
      })
      this.$store.commit('GOBACK_NAME', {
        oldUrl: oldUrl,
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    getSalaryStatus() {
      //获取工资表状态
      this.axios({
        method: 'post',
        url: 'api-su/cs/salary/expand/status',
        data: {},
      })
        .then((res) => {
          this.salaryStatusOptions = res.data.result
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取工资表状态数据失败',
            type: 'error',
          })
        })
    },
    // 搜索
    searchList() {
      if (this.date && this.date.length > 0) {
        let tempDate = this.date.split('-')
        this.filterField.year = tempDate[0]
        this.filterField.month = tempDate[1]
      } else {
        this.filterField.year = ''
        this.filterField.month = ''
      }
      this.$refs.pagination.getTableListData()
    },
    //跳转详情
    toDetail(index, row) {
      var queryData = {
        projectId: this.projectId,
        projectName: this.projectName,
        salaryId: row.id,
        yearQuery: row.year,
        statusQuery: row.status,
        from: this.message,
        batchNoInfo:
          row.year + '年' + row.month + '月第' + row.batchNo + '批次工资',
        monthQuery: row.month,
        batchNo: row.batchNo,
      }

      if (
        this.$route.query.delSalary &&
        this.$route.query.delSalary == 'delSalaryList'
      ) {
        queryData.delSalary = 'delSalaryList'
        this.$router.push({
          path: '/home/salaryDf/salaryPayBatchDetailList',
          name: 'salaryPayBatchDetailList',
          query: queryData,
        })
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/delSalary/salaryList',
          newUrl: this.$router.currentRoute.fullPath,
        })
      } else {
        queryData.safeguard = 'safeguard'
        this.$router.push({
          path: '/home/salaryDf/salaryPayBatchDetailList',
          name: 'salaryPayBatchDetailList',
          query: queryData,
        })
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/salaryDf/czSalaryPayList',
          newUrl: this.$router.currentRoute.fullPath,
        })
      }

      //   this.$store.commit('set_active_index',"/home/salaryDf/salaryPayList");
      //   this.$store.state.activeMenu ="/home/salaryDf/salaryPayList";
    },
    // 回传代发数据导入模板下载
    downLoad() {
      window.location.href =
        common.commonApi +
        'api-su/cs/salary/expand/bankSalaryTemplateDown?access_token=' +
        localStorage.getItem('access_token')
    },
    // downLoad(type) {
    //   this.axios({
    //     method: "post",
    //     url: "api-su/salary/expand/findurl",
    //     data: {
    //       name: type
    //     }
    //   })
    //     .then(response => {
    //       if (!response.data.hasError) {
    //         window.open(response.data.result.url);
    //       } else {
    //         this.$message({
    //           type: "error",
    //           message: response.data.msg
    //         });
    //       }
    //     })
    //     .catch(error => {});
    // },
    getvar(url, par) {
      var urlsearch = url.split('?')
      var pstr = urlsearch[1].split('&')
      for (var i = pstr.length - 1; i >= 0; i--) {
        var tep = pstr[i].split('=')
        if (tep[0] == par) {
          return tep[1]
        }
      }
      return false
    },

    closeDialog() {
      this.formVisible = false
    },
    // 滁州手动回传 ------start
    waterImportfileChangeCz(e, index, row) {
      var that = this
      var url = window.location.href
      var Filedata = e.target.value
      that.flieUpload.projectId = that.getvar(url, 'projectId')
      that.flieUpload.salaryId = row.id
      if (!/\.(xls|xlsx)$/.test(Filedata)) {
        this.$message({
          message: 'excel类型必须是.xls,xlsx中的一种',
          type: 'warning',
        })
        document.getElementById('waterImportfileChangeCz').value = ''
        return
      }

      setTimeout(function () {
        that.uploadFileByAjaxSubmitCz(
          'api-su/bank/manual/salaryImport',
          that.successCz,
          that.errorCz,
          e,
          row
        )
      }, 500)
    },
    uploadFileByAjaxSubmitCz(url, successCallBack, errorCallBack, e, row) {
      const vm = this
      var token = localStorage.getItem('access_token')
      var options = {
        url: common.uploadUrl + url,
        type: 'POST',
        dataType: 'json',
        data: vm.flieUpload,
        headers: { Authorization: 'Bearer ' + token },
        success: function (data) {
          e.target.value = ''
          successCallBack(data, row)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          e.target.value = ''
          errorCallBack(XMLHttpRequest, textStatus, errorThrown)
        },
      }

      //三种方式均可
      // $("#waterImportBox").ajaxSubmit(options);
      $(e.target.form).ajaxSubmit(options)
      return false
    },
    handleMsgLen(msg, len) {
      var new_msgName = ''
      if (msg.length > len) {
        new_msgName = msg.substring(0, len)
        new_msgName += '...'
      } else {
        new_msgName = msg
      }
      return new_msgName
    },
    successCz(data, row) {
      if (!data.hasError) {
        this.$message({
          message: data.msg,
          type: 'success',
        })
        this.$refs.pagination.getTableListData()
      } else {
        this.errorNotice = this.handleMsgLen(data.errorMsg, 200)
        this.formVisible = true
      }
    },
    //根据状态码判断是否是401
    errorCz(XMLHttpRequest, textStatus, errorThrown) {
      if (XMLHttpRequest.status === '401' || XMLHttpRequest.status === '403') {
        localStorage.setItem('access_token', '')
        localStorage.setItem('refresh_token', '')
        localStorage.setItem('userName', '')
        // 只有在当前路由不是登录页面才跳转
        if (router.currentRoute.path !== '/login/loginFirst') {
          router.replace({
            path: '/login/loginFirst',
          })
        }
        //清除tab栏数据
        this.$store.state.sliderBar = []
        localStorage.removeItem('sliderBar')
      } else {
        this.$message({
          message: '数据请求失败',
          type: 'warning',
        })
      }
    },
    // 手动回传 ------end
    getBankInfo() {
      this.axios({
        method: 'post',
        url: 'api-acc/account/expand/accountdetail',
        data: {
          projectId: this.projectId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            var data = response.data.result
            this.bankName = data.bankName
            this.bankSiteName = data.bankSiteName ? data.bankSiteName : ''
            this.account = data.account || ''
          }
        })
        .catch((error) => {})
    },
    toClearNetData(row) {
      this.$confirm('确认清除实发数据?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.clearNetData(row)
        })
        .catch(() => {})
    },
    clearNetData(row) {
      this.axios({
        method: 'post',
        url: 'api-su/bank/manual/czbsclean',
        data: {
          salaryId: row.id,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message({
              message: response.data.msg,
              type: 'success',
            })
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'warning',
            })
          }
        })
        .catch((error) => {})
    },
    toSyncData(row) {
      this.$confirm('确认同步?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.syncData(row)
        })
        .catch(() => {})
    },
    syncData(row) {
      this.axios({
        method: 'post',
        url: 'api-su/bank/manual/czbanksync',
        data: {
          salaryId: row.id,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message({
              message: response.data.msg,
              type: 'success',
            })
            this.$router.push({
              path: '/home/salaryDf/salaryPayBatchDetailList',
              name: 'salaryPayBatchDetailList',
              query: {
                projectId: this.projectId,
                projectName: this.projectName,
                salaryId: row.id,
                yearQuery: row.year,
                statusQuery: row.status,
                from: this.message,
                batchNoInfo:
                  row.year +
                  '年' +
                  row.month +
                  '月第' +
                  row.batchNo +
                  '批次工资',
                safeguard: 'safeguard',
                monthQuery: row.month,
                batchNo: row.batchNo,
              },
            })
            this.$store.commit('CHANGE_SLIDER_NAME', {
              oldUrl: '/home/salaryDf/czSalaryPayList',
              newUrl: this.$router.currentRoute.fullPath,
            })
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'warning',
            })
          }
        })
        .catch((error) => {})
    },
    //工资流水
    getBankSalaryDetail() {
      this.axios({
        method: 'post',
        url: 'api-m/paramconfig/findbyname',
        data: {
          name: 'bankSalaryDetail',
        },
      })
        .then((res) => {
          if (!res.data.hasError) {
            if (res.data.result.value == '1') {
              this.bankSalaryImport = true
            } else {
              this.bankSalaryImport = false
            }
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '数据请求失败，请重试',
            type: 'error',
          })
        })
    },
  },
}
</script>

<style lang="less" scoped>
.titleBoxOut {
  background: #fff;
  padding: 0 24px;
}
.titleBox {
  border-bottom: 1px solid #e3e7e9;
  padding: 15px 0px;
  margin-bottom: 0;
  .blockTitle {
    font-weight: bold;
    font-size: 18px;
    color: #333;
    line-height: 40px;
    .iconfanhui1 {
      font-size: 20px;
      margin-right: 6px;
      cursor: pointer;
    }
  }
  .code {
    font-size: 14px;
    color: #666;
    margin-left: 30px;
  }
  .goSeeDetail {
    font-size: 14px;
    margin-left: 30px;
  }
}
.mainCon {
  //   overflow-y: auto;
  background: #fff;
  //   padding-left: 24px;
  //   padding-right: 24px;
}
.uploadBox {
  text-align: center;
  padding: 20px;
}
.imgStyle {
  margin-top: 20px;
  li {
    position: relative;
    margin-right: 20px;
    margin-top: 10px;
    i {
      position: absolute;
      right: -6px;
      top: -10px;
      font-size: 20px;
    }
  }
}

.manualPostbackBox {
  position: relative;
  .upLoadDom {
    position: absolute;
    width: 96px;
    height: 25px;
    top: 0;
    left: 0;
    opacity: 0;
    line-height: 0px;
    form {
      input {
        width: 96px;
        height: 25px;
        line-height: 0px;
        cursor: pointer;
      }
    }
  }
}
.errorNoticeBox {
  text-align: center;
  margin-bottom: 24px;
  i {
    color: red;
    font-size: 50px;
  }
}
.errorBox {
  line-height: 24px;
}
@import '../../../static/css/filterArea.less';
</style>
